import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import api from '@/services/api'

export const useAuthStore = defineStore('auth', () => {
  // 状态
  const token = ref(localStorage.getItem('token') || '')
  const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))

  // 计算属性
  const isAuthenticated = computed(() => !!token.value)
  const userRoles = computed(() => user.value?.roles || [])

  // 检查用户是否有特定角色
  const hasRole = (roleName) => {
    console.log('检查角色:', roleName, '用户角色:', userRoles.value)

    // 确保用户角色是数组
    if (!Array.isArray(userRoles.value)) {
      console.error('用户角色不是数组:', userRoles.value)
      return false
    }

    // 检查用户是否有指定角色
    const hasTheRole = userRoles.value.includes(roleName)
    console.log('角色检查结果:', hasTheRole)
    return hasTheRole
  }

  // 检查用户是否是管理员
  const isAdmin = computed(() => {
    const result = hasRole('admin')
    console.log('管理员检查结果:', result)
    return result
  })

  // 设置token
  const setToken = (newToken) => {
    token.value = newToken
    localStorage.setItem('token', newToken)
  }

  // 设置用户信息
  const setUser = (newUser) => {
    user.value = newUser
    localStorage.setItem('user', JSON.stringify(newUser))
  }

  // 登出
  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
  }

  // 获取当前用户信息
  const fetchCurrentUser = async () => {
    try {
      const response = await api.getCurrentUser()
      setUser(response.data.user)
      return response.data.user
    } catch (error) {
      console.error('获取用户信息失败:', error)
      logout()
      throw error
    }
  }

  // 刷新令牌
  const refreshToken = async () => {
    try {
      console.log('尝试刷新令牌...')

      // 确保我们有用户名
      if (!user.value || !user.value.username) {
        console.error('无法刷新令牌: 缺少用户名')
        throw new Error('缺少用户名')
      }

      const response = await api.refreshToken(user.value.username)
      console.log('令牌刷新成功:', response.data)

      // 保存新的令牌和用户信息
      const newToken = response.data.token
      setToken(newToken)
      setUser(response.data.user)

      // 返回新的令牌
      return newToken
    } catch (error) {
      console.error('刷新令牌失败:', error)
      logout()
      throw error
    }
  }

  return {
    token,
    user,
    isAuthenticated,
    userRoles,
    isAdmin,
    hasRole,
    setToken,
    setUser,
    logout,
    fetchCurrentUser,
    refreshToken
  }
})
